<template>
  <!-- 模具邮件发送配置表表单弹窗 -->
  <el-dialog
    v-model="visibleDialog"
    :title="props.title"
    width="1100px"
    draggable
    @close="closeDialog"
  >
    <div style="height: 600px; overflow-y: auto">
      <div v-show="props.isReadonly">
        <el-descriptions
          class="margin-top"
          title=""
          :column="1"
          size="large"
          border
        >
          <el-descriptions-item>
            <template #label>
              <div class="cell-item">产品</div>
            </template>
            <div style="width: 80%; word-break: break-all">
              {{ formData.productName }}
            </div>
          </el-descriptions-item>
          <el-descriptions-item>
            <template #label>
              <div class="cell-item">阶段</div>
            </template>
            <div style="width: 80%; word-break: break-all">
              {{ formData.sendStageName }}
            </div>
          </el-descriptions-item>

          <el-descriptions-item :span="2">
            <template #label>
              <div class="cell-item">发送标题</div>
            </template>
            <div style="width: 80%; word-break: break-all">
              {{ formData.sendTitle }}
            </div>
          </el-descriptions-item>
        </el-descriptions>
        <div
          style="
            display: flex;
            justify-content: space-between;
            align-items: center;
          "
        >
          <h4 class="mb-[20px] mt-[20px]">检验角色列表</h4>
        </div>
        <div class="formTable">
          <el-table
            :data="formData.checkRoleList"
            style="width: 100%"
            :key="Math.random"
            border
          >
            <el-table-column
              type="index"
              label="序号"
              align="center"
              width="100"
            />
            <el-table-column
              label="角色名"
              props="roleName"
              min-width="150"
              align="center"
            >
              <template #default="{ $index, row }">
                <span>{{ row.roleName }}</span>
              </template>
            </el-table-column>
          </el-table>
        </div>
        <div
          style="
            display: flex;
            justify-content: space-between;
            align-items: center;
          "
        >
          <h4 class="mb-[20px] mt-[20px]">判定角色列表</h4>
        </div>
        <div class="formTable">
          <el-table
            :data="formData.judgRoleList"
            style="width: 100%"
            :key="Math.random"
            border
          >
            <el-table-column
              type="index"
              label="序号"
              align="center"
              width="100"
            />
            <el-table-column
              label="角色名"
              props="roleName"
              min-width="150"
              align="center"
            >
              <template #default="{ $index, row }">
                <span>{{ row.roleName }}</span>
              </template>
            </el-table-column>
          </el-table>
        </div>
      </div>
      <el-form
        ref="formRef"
        :model="formData"
        :rules="rules"
        label-width="160"
        v-show="!props.isReadonly"
      >
        <el-row>
          <el-col :span="24">
            <el-transfer
              :data="productIds"
              style="
                text-align: center;
                display: inline-block;
                width: 100%;
                min-width: 100%;
              "
              :filterable="true"
              :props="{
                key: 'id',
                label: 'materialName',
              }"
              :titles="['可用产品', '已选产品']"
              v-model="formData.productIds"
            />
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="20" :offset="1">
            <el-form-item label="阶段" prop="sendStage" label-width="80px">
              <el-checkbox-group v-model="formData.sendStageList">
                <el-checkbox
                  v-for="lifeConfig in lifeConfigList"
                  :label="lifeConfig.checkLabel"
                  :key="lifeConfig.reminderLife"
                  :value="lifeConfig.checkLabel"
                  >{{ lifeConfig.reminderName }}</el-checkbox
                >
              </el-checkbox-group>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="20" :offset="1">
            <el-form-item label="发送标题" prop="sendTitle" label-width="80px">
              <el-input
                maxlength="100"
                v-if="!props.isReadonly"
                v-model="formData.sendTitle"
                placeholder="请输入发送标题"
                show-word-limit
                clearable
              />
            </el-form-item>
          </el-col>

          <el-col :span="18" :offset="3">
            <div
              style="
                display: flex;
                justify-content: space-between;
                align-items: center;
              "
              v-if="!props.isReadonly"
            >
              <h4 class="mb-[20px] mt-[20px]">检验角色列表</h4>
              <el-button
                type="success"
                plain
                @click="handleAddLeader"
                v-if="!props.isReadonly"
              >
                <i-ep-plus />
                新增
              </el-button>
            </div>
            <div class="formTable">
              <el-table
                :data="formData.checkRoleList"
                style="width: 100%"
                :key="Math.random"
                border
                v-if="!props.isReadonly"
              >
                <el-table-column
                  type="index"
                  label="序号"
                  align="center"
                  width="100"
                />
                <el-table-column
                  label="角色名"
                  props="roleName"
                  min-width="150"
                  align="center"
                >
                  <template #default="{ $index, row }">
                    <span>{{ row.roleName }}</span>
                  </template>
                </el-table-column>

                <el-table-column
                  fixed="right"
                  align="center"
                  label="操作"
                  width="100"
                  v-if="!props.isReadonly"
                >
                  <template #default="scope">
                    <el-button
                      type="danger"
                      link
                      @click.stop="handleDeleteLeader(scope.$index)"
                      ><i-ep-delete />
                      删除
                    </el-button>
                  </template>
                </el-table-column>
              </el-table>
            </div>
          </el-col>
          <el-col :span="18" :offset="3">
            <div
              style="
                display: flex;
                justify-content: space-between;
                align-items: center;
              "
              v-if="!props.isReadonly"
            >
              <h4 class="mb-[20px] mt-[20px]">判定角色列表</h4>
              <el-button
                type="success"
                plain
                @click="handleAddLeader2"
                v-if="!props.isReadonly"
              >
                <i-ep-plus />
                新增
              </el-button>
            </div>
            <div class="formTable">
              <el-table
                :data="formData.judgRoleList"
                style="width: 100%"
                :key="Math.random"
                border
                v-if="!props.isReadonly"
              >
                <el-table-column
                  type="index"
                  label="序号"
                  align="center"
                  width="100"
                />
                <el-table-column
                  label="角色名"
                  props="roleName"
                  min-width="150"
                  align="center"
                >
                  <template #default="{ $index, row }">
                    <span>{{ row.roleName }}</span>
                  </template>
                </el-table-column>

                <el-table-column
                  fixed="right"
                  align="center"
                  label="操作"
                  width="100"
                  v-if="!props.isReadonly"
                >
                  <template #default="scope">
                    <el-button
                      type="danger"
                      link
                      @click.stop="handleDeleteLeader2(scope.$index)"
                      ><i-ep-delete />
                      删除
                    </el-button>
                  </template>
                </el-table-column>
              </el-table>
            </div>
          </el-col>
        </el-row>
      </el-form>
    </div>
    <template #footer>
      <div class="dialog-footer">
        <el-button
          v-if="!props.isReadonly"
          type="primary"
          :loading="loading"
          @click="handleSubmit"
          >确 定</el-button
        >
        <el-button @click="closeDialog">取 消</el-button>
      </div>
    </template>
  </el-dialog>
  <eammouldemailconfig-select
    :visible="selectDialogLeader.visible"
    :data="breakListLeader"
    :title="selectDialogLeader.title"
    @change-visible-leader="changeVisibleLeader"
  />
  <eammouldemailconfig-select
    :visible="selectDialogLeader2.visible"
    :data="breakListLeader2"
    :title="selectDialogLeader2.title"
    @change-visible-leader="changeVisibleLeader2"
  />
</template>

<script setup lang="ts">
import request from "@/utils/request";
import { useDictStoreHook } from "@/store/modules/dictionary"; // 引入
import { log } from "console";
const dictionaryStore = useDictStoreHook();

defineOptions({
  name: "EAMMOLDEAMMOULDEMAILCONFIGADDORUPDATE",
  inheritAttrs: false,
});

const emit = defineEmits(["reset-table", "change-visible"]);

const props = defineProps({
  visible: {
    type: Boolean,
    default: () => {
      return false;
    },
  },
  title: {
    type: String,
    default: () => {
      return "";
    },
  },
  data: {
    type: Object,
    default: () => {
      return {};
    },
  },
  isReadonly: {
    type: Boolean,
    default: () => {
      return false;
    },
  },
});

const visibleDialog = ref(false);
watch(
  () => props.visible,
  (newVal: boolean) => {
    getLifeConfigList();
    visibleDialog.value = newVal;
    setTimeout(() => {
      formRef.value.clearValidate();
    }, 50);
  }
);
const rules = reactive({
  sendStage: [],
  sendRoleId: [
    { min: 1, max: 500, message: "长度在 1 到 500 个字符", trigger: "blur" },
  ],
  sendTitle: [
    { required: true, message: "请输入标题", trigger: "blur" },
    { min: 1, max: 255, message: "长度在 1 到 255 个字符", trigger: "blur" },
  ],
  sendContent: [
    { min: 1, max: 255, message: "长度在 1 到 255 个字符", trigger: "blur" },
  ],
  productIds: [],
  alramQuantity: [],
});

const formRef = ref(ElForm);

let formData = reactive({
  id: "",
  sendStage: 1,
  sendRoleId: "",
  sendRoleName: "",
  sendTitle: "",
  sendContent: "",
  productId: "",
  productCode: "",
  productName: "",
  alramQuantity: 0,
  enabled: "",
  deleted: "",
  createTime: "",
  createdUserId: "",
  createdUserName: "",
  lastUpdateTime: "",
  lastUpdatedUserId: "",
  lastUpdatedUserName: "",
  productIds: [],
  sendStageList: [],
  checkRoleList: [],
  judgRoleList: [],
  sendStageName: "",
});

watch(
  () => props.data,
  (newVal: any) => {
    formData.id = "";
    if (newVal?.id) {
      const {
        id,
        sendStage,
        sendRoleId,
        sendRoleName,
        sendTitle,
        sendContent,
        productId,
        productCode,
        productName,
        alramQuantity,
        enabled,
        deleted,
        createTime,
        createdUserId,
        createdUserName,
        lastUpdateTime,
        lastUpdatedUserId,
        lastUpdatedUserName,
        productIds,
        sendStageList,
        checkRoleList,
        judgRoleList,
        sendStageName,
      } = newVal;
      Object.assign(formData, {
        id,
        sendStage,
        sendRoleId,
        sendRoleName,
        sendTitle,
        sendContent,
        productId,
        productCode,
        productName,
        alramQuantity,
        enabled,
        deleted,
        createTime,
        createdUserId,
        createdUserName,
        lastUpdateTime,
        lastUpdatedUserId,
        lastUpdatedUserName,
        productIds,
        sendStageList,
        checkRoleList,
        judgRoleList,
        sendStageName,
      });
    }
  }
);

/** 关闭表单弹窗 */
function closeDialog() {
  visibleDialog.value = false;
  emit("change-visible", false);
  resetForm();
}

/** 重置表单 */
function resetForm() {
  formRef.value.resetFields();
  formRef.value.clearValidate();
  formData.id = "";
  formData.sendStage = 1;
  formData.sendRoleId = "";
  formData.sendRoleName = "";
  formData.sendTitle = "";
  formData.sendContent = "";
  formData.productId = "";
  formData.productCode = "";
  formData.productName = "";
  formData.alramQuantity = 0;
  formData.enabled = "";
  formData.deleted = "";
  formData.createTime = "";
  formData.createdUserId = "";
  formData.createdUserName = "";
  formData.lastUpdateTime = "";
  formData.lastUpdatedUserId = "";
  formData.lastUpdatedUserName = "";
  formData.productIds = [];
  formData.sendStageList = [];
  formData.checkRoleList = [];
  formData.judgRoleList = [];
  formData.sendStageName = "";
}

const loading = ref(false);

/** 模具邮件发送配置表保存提交 */
function handleSubmit() {
  formRef.value.validate(async (valid: any) => {
    if (valid) {
      loading.value = true;
      const text = formData.id ? "编辑" : "新增";
      await request({
        url: "/eam/eammouldemailconfig/save",
        method: "post",
        data: formData,
      }).finally(() => {
        loading.value = false;
      });
      ElMessage.success(text + `成功`);
      closeDialog();
      emit("reset-table", formData.id);
    }
  });
}

// 组件销毁时调用
onBeforeUnmount(() => {
  visibleDialog.value = false;
  emit("change-visible", false);
});

const productIds = ref([]);
const getProductList = async () => {
  const { data } = await request({
    url: "/mdm/mdmmaterial/getList",
    method: "POST",
    data: { materialType: "3" },
  });
  productIds.value = data;
};

const lifeConfigList = ref([]);
const getLifeConfigList = async () => {
  const { data } = await request({
    url: "/eam/eammouldlifeconfig/getList",
    method: "POST",
    data: {},
  });
  lifeConfigList.value = data;
};

onMounted(() => {
  getProductList();
  getLifeConfigList();
});

/** 添加行 */
const handleAddLeader = () => {
  // let sondata = JSON.parse(JSON.stringify(details));
  // formData.details.push(sondata);
  selectDialogLeader.value.title = "选择领导人";
  selectDialogLeader.value.visible = true;
  console.log(formData);

  if (formData.checkRoleList.length > 0) {
    getBreakListLeader();
  }
};

const handleAddLeader2 = () => {
  // let sondata = JSON.parse(JSON.stringify(details));
  // formData.details.push(sondata);
  selectDialogLeader2.value.title = "选择领导人";
  selectDialogLeader2.value.visible = true;

  if (formData.judgRoleList.length > 0) {
    getBreakListLeader2();
  }
};

const selectDialogLeader = ref({
  visible: false,
  title: "",
});
const selectDialogLeader2 = ref({
  visible: false,
  title: "",
});
const changeVisibleLeader = (val: boolean, data: any) => {
  if (data) {
    formData.checkRoleList = [];
    data.forEach((item) => {
      formData.checkRoleList.push({
        roleId: item.id,
        roleName: item.roleName,
        roleType: 1,
      });
    });
  }

  selectDialogLeader.value.visible = val;
};
const changeVisibleLeader2 = (val: boolean, data: any) => {
  if (data) {
    formData.judgRoleList = [];
    data.forEach((item) => {
      formData.judgRoleList.push({
        roleId: item.id,
        roleName: item.roleName,
        roleType: 2,
      });
    });
  }
  selectDialogLeader2.value.visible = val;
};

// 新增完返回的数据用于显示选择器
const breakListLeader = ref([]);
const getBreakListLeader = () => {
  breakListLeader.value = [];
  formData.checkRoleList.forEach((item) => {
    breakListLeader.value.push({
      id: item.roleId,
      roleName: item.roleName,
    });
  });
};

const breakListLeader2 = ref([]);
const getBreakListLeader2 = () => {
  breakListLeader2.value = [];
  formData.judgRoleList.forEach((item) => {
    breakListLeader2.value.push({
      id: item.roleId,
      roleName: item.roleName,
    });
  });
};
const isValidated = ref(false);
const isValidated2 = ref(false);
/** 删除行 */
const handleDeleteLeader = (index: any) => {
  formData.checkRoleList.splice(index, 1);
  isValidated.value && formRef.value.validate(() => {});
};
const handleDeleteLeader2 = (index: any) => {
  formData.judgRoleList.splice(index, 1);
  isValidated2.value && formRef.value.validate(() => {});
};
</script>
<style scoped lang="scss">
:deep(.el-transfer .el-transfer-panel) {
  width: 300px;
}
</style>
